package com.moco.launcher.view;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Paint.Style;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.moco.launcher.R;
import com.moco.launcher.bean.PickItemInfo;
import com.oazon.common.Logger;
import com.oazon.common.TaskHelper;
import com.oazon.common.util.Utils;

/**
 * 
 * http://bLogger.csdn.net/zhongkejingwang/article/details/38513301
 * 
 * @author chenjing
 * 
 */
public class CategoryPickerView extends View {

	public static final String TAG = "CategoryPickerView";

	public static final float MARGIN_ALPHA = 2.2f;// 2.8f;

	public static final float SPEED = 2;

	private List<PickItemInfo> mDataList;
	public int mCurrentSelected;
	private Paint mPaint;

	public float mMaxTextSize = 160;
	private float mMinTextSize = 80;

	private float mMaxTextAlpha = 255;
	private float mMinTextAlpha = 120;
	private float mMarginWidth = 0;

	private int mColorText = 0xFFFFFFF;
	private int shadowColorText = 0xFF000000;

	private int mViewHeight;
	private int mViewWidth;

	private float mLastDownY;
	private Context mContext = null;
	/**
	 * �����ľ���
	 */
	private float mMoveLen = 0;
	private boolean isInit = false;
	private onSelectListener mSelectListener;
	private Timer timer;
	private MyTimerTask mTask = null;
	UiParam mHlParam = new UiParam();

	private float step = 0.0f;
	private boolean l2r = true;
	private float aWordWith = 0.0f;
	private float y = 0;
	public float clickY = 0;
	public static boolean isUp = false;

	Handler updateHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (Math.abs(mMoveLen) < 1) {
				mMoveLen = 0;
				if (mTask != null) {
					mTask.cancel();
					mTask = null;
				}
			} else {
				mMoveLen = mMoveLen - mMoveLen / Math.abs(mMoveLen) * SPEED;
				invalidate();
			}
		}
	};

	public CategoryPickerView(Context context) {
		super(context);
		init();
	}

	public CategoryPickerView(Context context, AttributeSet attrs) {
		super(context, attrs);

		TypedArray a = context.obtainStyledAttributes(attrs,
				R.styleable.PickerView);
		mMarginWidth = a.getDimension(R.styleable.PickerView_margin_width, 0);
		a.recycle();
		mContext = context;
		init();
		this.setFilterTouchesWhenObscured(true);
		startMoveTxt();
	}

	public void setOnSelectListener(onSelectListener listener) {
		mSelectListener = listener;
	}

	public String getCurrentSelectId(int icurrentSlect) {
		if (mDataList.size() == 0 || icurrentSlect >= mDataList.size()
				|| icurrentSlect < 0)
			return "";

		return mDataList.get(icurrentSlect).getId();
	}

	public String getCurrentSelectText() {
		PickItemInfo info = getItemBean();
		if (mDataList.size() == 0 || info == null)
			return "";

		return info.getText();
	}

	public void setData(List<PickItemInfo> datas) {
		mDataList = datas;
		mCurrentSelected = 1;
		step = 0;
	}

	public void setSelected(int selected) {
		if (selected == -1) {
			selected = 1;
		}
		mCurrentSelected = selected;
		step = 0;
	}

	private void moveHeadToTail() {
		PickItemInfo head = mDataList.get(0);
		mDataList.remove(0);
		mDataList.add(head);
	}

	private void moveTailToHead() {
		PickItemInfo tail = mDataList.get(mDataList.size() - 1);
		mDataList.remove(mDataList.size() - 1);
		mDataList.add(0, tail);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		mViewHeight = getMeasuredHeight();
		mViewWidth = getMeasuredWidth();
		// ����View�ĸ߶ȼ��������С
		mMaxTextSize = mViewHeight / 4.0f;
		mMinTextSize = mMaxTextSize / 2.0f;
		isInit = true;
		invalidate();
	}

	private void init() {
		timer = new Timer();
		mDataList = new ArrayList<PickItemInfo>();
		mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		mPaint.setStyle(Style.FILL);
		mPaint.setTextAlign(Align.CENTER);
		mPaint.setColor(mColorText);
		mPaint.setShadowLayer(1, 2, 2, shadowColorText);

		aWordWith = mPaint.measureText("一");
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		Logger.d(TAG, "isInit" + isInit);
		if (isInit)
			drawData(canvas);
	}

	private void drawSelected(Canvas canvas) {
		// 先绘制选中的text再往上往下绘制其余的text
		float scale = parabola(mViewHeight / 4.0f, mMoveLen);
		mMarginWidth = 0;
		float size = ((mMaxTextSize - mMinTextSize) * scale + mMinTextSize) / 2f;
		mPaint.setTextSize(size);
		if (this.mSelectListener != null) {
			if (this.mSelectListener.onRelayout(
					getCurrentSelectId(mCurrentSelected), mHlParam)) {
				mMarginWidth = mHlParam.nMarginWidth;
				mPaint.setColor(mHlParam.HlColor);
			}
			// mPaint.setTextSize(size/3);
		}

		mPaint.setAlpha((int) ((mMaxTextAlpha - mMinTextAlpha) * scale + mMinTextAlpha));

		// text居中绘制，注意baseline的计算才能达到居中，y值是text中心坐标
		float x = (float) (mViewWidth / 2.0);
		float y = (float) (mViewHeight / 2.0 + mMoveLen);
		FontMetricsInt fmi = mPaint.getFontMetricsInt();
		float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0));

		PickItemInfo item = getItemBean();
		if (item == null) {
			return;
		}
		String text = item.getText();

		if (item.getBackIconId() != -1) {
			Bitmap bm = BitmapFactory.decodeResource(getResources(),
					item.getBackIconId());
			float x1 = (mViewWidth / 2 - bm.getWidth() / 2);
			float y1 = (float) (mViewHeight / 2.0 - bm.getHeight() / 2.0 + mMoveLen);
			canvas.drawBitmap(bm, x1, y1, mPaint);

		}

		if (item.getLeftIconLight() != -1) {

			Bitmap bm = BitmapFactory.decodeResource(getResources(),
					item.getLeftIconLight());
			float x1 = mViewWidth / 2 - mPaint.measureText(text) / 2
					- bm.getWidth() - aWordWith;
			float y1 = (float) (mViewHeight / 2.0 - bm.getHeight() / 2.0 + mMoveLen);
			canvas.drawBitmap(bm, x1, y1, mPaint);
		}

		/*
		 * Logger.d(TAG, "mMoveLen = " + mMoveLen); Logger.d(TAG,
		 * "mViewHeight = " + mViewHeight); Logger.d(TAG, "mViewWidth = " +
		 * mViewWidth); Logger.d(TAG, "mMaxTextSize = " + mMaxTextSize);
		 * Logger.d(TAG, "mMinTextSize = " + mMinTextSize); Logger.d(TAG,
		 * "MARGIN_ALPHA = " + MARGIN_ALPHA); Logger.d(TAG, "scale = " + scale);
		 * Logger.d(TAG, "size = " + size); Logger.d(TAG, "x = " + x);
		 * Logger.d(TAG, "baseline = " + baseline); Logger.d(TAG, "text = " +
		 * text); Logger.d(TAG, "\n\n");
		 */
		float moveX = 0;
		float strwidth = mPaint.measureText(text);

		if (strwidth > getwordMaxWidth()) {
			releceMoveTxtPause();
			mMarginWidth = -strwidth / 2 + x * 7f / 8f;
		}
		moveX = x - mMarginWidth - step;
		if (moveX >= x + strwidth / 2 - x * 7f / 8f) {
			l2r = true;
		} else if (moveX <= x - strwidth / 2 + x * 7f / 8f) {
			l2r = false;
		}
		if (moveX < 0)
			moveX = 0;
		canvas.drawText(text, moveX, baseline, mPaint);

	}

	private PickItemInfo getItemBean() {
		if (mDataList == null || mCurrentSelected >= mDataList.size()
				|| mCurrentSelected < 0) {
			return null;
		}
		return mDataList.get(mCurrentSelected);
	}

	@Override
	public void setOnClickListener(OnClickListener l) {

		super.setOnClickListener(l);
	}

	private void startMoveTxt() {
		isRunning = true;
		TaskHelper.exec(new moveTxtRunnable());
	}

	public void stopMoveTxt() {
		moveTxtHandler.removeMessages(1);
		isRunning = false;
		step = 0;
		l2r = true;
		Logger.i(TAG, "stopMoveTxt");
	}

	private boolean isRunning = false;
	private boolean isPause = false;

	public class moveTxtRunnable implements Runnable {

		@Override
		public void run() {

			while (isRunning) {
				if (mPaint.measureText(getCurrentSelectText()) > getwordMaxWidth()
						&& !isPause) {

					if (l2r) {
						step += 2.0f;
					} else {
						step -= 2.0f;
					}
					moveTxtHandler.sendEmptyMessage(1);
					try {
						Thread.sleep(50);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}

	}

	Handler moveTxtHandler = new Handler() {
		public void handleMessage(Message msg) {
			invalidate();
		};
	};

	private void drawData(Canvas canvas) {
		if (this.mDataList.size() == 0)
			return;

		drawSelected(canvas);

		for (int i = 1; (mCurrentSelected - i) >= 0; i++) {
			drawOtherText(canvas, i, -1);
		}

		for (int i = 1; (mCurrentSelected + i) < mDataList.size(); i++) {
			drawOtherText(canvas, i, 1);
		}
	}

	/**
	 * @param canvas
	 * @param position
	 *            ����mCurrentSelected�Ĳ�ֵ
	 * @param type
	 *            1��ʾ���»��ƣ�-1��ʾ���ϻ���
	 */
	private void drawOtherText(Canvas canvas, int position, int type) {
		float d = (float) (MARGIN_ALPHA * mMinTextSize * position + type
				* mMoveLen) + 20f;

		float scale = parabola(mViewHeight / 2.0f, d);
		float size = ((mMaxTextSize - mMinTextSize) * scale + mMinTextSize) / 2f;

		mPaint.setColor(mHlParam.Color);
		mPaint.setTextSize(size);
		mPaint.setAlpha((int) ((mMaxTextAlpha - mMinTextAlpha) * scale + mMinTextAlpha));

		float y = (float) (mViewHeight / 2 + type * d);

		/*
		 * Logger.d(TAG, "internal " + internal); Logger.d(TAG, "y " + y);
		 */

		FontMetricsInt fmi = mPaint.getFontMetricsInt();
		float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0));

		PickItemInfo item = mDataList.get(mCurrentSelected + type * position);
		String text = item.getText();

		/*
		 * Logger.d(TAG, "text = " + text); Logger.d(TAG, "\n\n");
		 */
		if (item.getLeftIconDark() != -1) {
			Bitmap bm = BitmapFactory.decodeResource(getResources(),
					item.getLeftIconDark());
			float x1 = mViewWidth / 2 - mPaint.measureText(text) / 2
					- bm.getWidth() - aWordWith;
			canvas.drawBitmap(
					bm,
					x1,
					baseline - bm.getHeight()
							- (bm.getHeight() - Utils.getFontHeight(size)) / 2,
					mPaint);
		}

		String tempTex = "";
		if (mPaint.measureText(text) > Utils.dip2px(mContext, 180)) {
			for (int i = 0; i < 10; i++) {
				if (mPaint.measureText(text.substring(0, 7 + i) + "...") > Utils
						.dip2px(mContext, 180)) {
					tempTex = text.substring(0, 7 + i) + "...";
					break;
				} else {// 修改某些字符显示不出来的情况
					tempTex = text.substring(0, 7 + i) + "...";
				}
			}
		} else {
			tempTex = text;
		}
		// Logger.i(TAG, "tempTex==" + tempTex);
		canvas.drawText(tempTex, (float) (mViewWidth / 2.0), baseline, mPaint);

	}

	/**
	 * ������
	 * 
	 * @param zero
	 *            ������
	 * @param x
	 *            ƫ����
	 * @return scale
	 */
	private float parabola(float zero, float x) {
		float f = (float) (1 - Math.pow(x / zero, 2));
		return f < 0 ? 0 : f;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		switch (event.getActionMasked()) {

		case MotionEvent.ACTION_DOWN:
			clickY = event.getY();
			y = event.getY();
			doDown(event);
			isUp = false;
			break;
		case MotionEvent.ACTION_MOVE:
			doMove(event);
			Logger.d("TAG",
					"Math.abs(y-event.getY())=" + Math.abs(y - event.getY()));
			if (Math.abs(event.getY() - y) > 20)
				isUp = true;
			break;
		case MotionEvent.ACTION_UP:
			doUp(event);
			break;
		}

		// TODO Auto-generated method stub

		/*
		 * if ((event.getY() < (this.getHeight() / 2 - this.mMaxTextSize / 2))
		 * || (event.getY() > this.getHeight() / 2 + this.mMaxTextSize / 2)){
		 * Logger.e("test", "点击中间面"); return true; } if((event.getY() >
		 * this.getHeight() / 2 + this.mMaxTextSize / 2)){ Logger.e("test",
		 * "点击下面"); return true; }
		 */

		/*
		 * if ((event.getY() < (this.getHeight() / 2 - this.mMaxTextSize / 2))
		 * || (event.getY() > this.getHeight() / 2 + this.mMaxTextSize / 2))
		 */
		// return true;

		return super.onTouchEvent(event);
	}

	private void doDown(MotionEvent event) {
		Logger.d(TAG, "========doDown");
		if (mTask != null) {
			mTask.cancel();
			mTask = null;
		}
		mLastDownY = event.getY();
		pauseMoveTxt();
	}

	private void doMove(MotionEvent event) {
		Logger.d(TAG, "========doMove");
		step = 0;
		if (this.mDataList.size() == 0)
			return;
		mMoveLen += (event.getY() - mLastDownY);

		if (mMoveLen > MARGIN_ALPHA * mMinTextSize / 2) {
			moveTailToHead();
			mMoveLen = mMoveLen - MARGIN_ALPHA * mMinTextSize;
		} else if (mMoveLen < -MARGIN_ALPHA * mMinTextSize / 2) {
			moveHeadToTail();
			mMoveLen = mMoveLen + MARGIN_ALPHA * mMinTextSize;
		}

		mLastDownY = event.getY();
		invalidate();
	}

	private void doUp(MotionEvent event) {
		Logger.d(TAG, "========doUp");
		if (Math.abs(mMoveLen) < 0.0001) {
			mMoveLen = 0;
			return;
		}
		if (mTask != null) {
			mTask.cancel();
			mTask = null;
		}
		if (mSelectListener != null) {
			mSelectListener.onStop(getCurrentSelectId(mCurrentSelected));
		}
		if (mPaint.measureText(getCurrentSelectText()) > getwordMaxWidth()) {
			releceMoveTxtPause();
		}
		startUpdateView();
	}

	public void startUpdateView() {
		if (mTask == null) {
			mTask = new MyTimerTask(updateHandler);
			timer.schedule(mTask, 0, 10);
		}
	}

	public void pauseMoveTxt() {
		step = 0;
		isPause = true;
	}

	public void releceMoveTxtPause() {
		isPause = false;
		invalidate();
	}

	class MyTimerTask extends TimerTask {
		Handler handler;

		public MyTimerTask(Handler handler) {
			this.handler = handler;
		}

		@Override
		public void run() {
			handler.sendMessage(handler.obtainMessage());
		}
	}

	public class UiParam {
		public int Color = 0xFFFFFFF;
		public int HlColor = 0xFFFFFFF;
		public float nMarginWidth = 0;
	}

	public interface onSelectListener {
		boolean onRelayout(String nSelectId, UiParam param);

		boolean onSelect(String nSelectId);

		boolean onStop(String nSelectId);
	}

	private float getwordMaxWidth() {
		float wordMaxWidth = mPaint.measureText("我是测试字符长度!");
		return wordMaxWidth;
	}
}
